<?php

namespace Common\Model;
use Think\Model;

class CaseLogicModel extends Model {

	protected $tableName = 'patient';

  /**
   * 获取病人交接状态
   * @param $patientId
   */
  public function getCaseStatus($patientId){
    $patient = $this->find($patientId);
    if(empty($patient)){
      return ['car_close'=>0,'hospital_close'=>0];
    }

    return [
        'car_close'=> (int)$patient['car_close'] ,
        'hospital_close'=>(int)$patient['hospital_close'],
        'case_close'=>(int)( (int)$patient['car_close'] && (int)$patient['hospital_close'] ),
    ];
  }

  /**
   * 120交接逻辑
   * @param car_id,$patient_id,$signature
   */
  public function closeCase($carId,$patientId,$signature,$userCarId){
    if(empty($signature)){
      return ['status'=>0,'error_info'=>'需要提交签名'];
    }

    $patient = $this->where(['car_id'=>$carId,'id'=>$patientId])->find();
    if(empty($patient)){
      return ['status'=>0,'error_info'=>'未找到病人'];
    }

    if($patient['user120_id'] != $userCarId){
      return ['status'=>0,'error_info'=>'您未负责该病人，不能提交交接请求'];
    }

    if($patient['car_close']==1){
      return ['status'=>0,'error_info'=>'已经交接成功，请勿重复交接'];
    }

    //TODO:: 可能会有交接前的检查逻辑
    $this->car_close = 1;
    $this->car_close_time = time();
    $this->car_signature = $signature;
    if($this->save()){
      return ['status'=>1];
    }else{
      return ['status'=>0,'error_info'=>'保存失败'];
    }
  }

  /**
   * 医院查询是否可以交接接口
   */
  public function checkCloseStatus($patientId){
    $patient = $this->find($patientId);
    if(empty($patient)){
      return ['status'=>0,'error_info'=>'未找到病人'];
    }

    //TODO:: 可能会有交接前的检查逻辑

    if($patient['car_close'] == 1){
      //可以交接
      return ['status'=>1];
    }

    return ['status'=>0,'error_info'=>'120端用户还没有交接，请等待'];
  }

  /**
   * 医院交接病人
   * @param patient_id,signature
   */
  public function closeCaseForHospital($patientId,$signature){
    $patient = $this->find($patientId);
    if(empty($patient)){
      return ['status'=>0,'error_info'=>'未找到病人123123'];
    }

    if($patient['hospital_close']==1){
      return ['status'=>0,'error_info'=>'已经交接成功，请勿重复交接'];
    }

    //TODO:: 可能会有交接前的检查逻辑

    $this->hospital_close = 1;
    $this->hospital_close_time = time();
    $this->hospital_signature = $signature;
    if($this->save()){
      return ['status'=>1];
    }else{
      return ['status'=>0,'error_info'=>'保存失败'.$this->getError()];
    }
  }

}